/*
 * BanBu_WebFrame_ViewController
 * @description 本文件提供半圆测试平台界面的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供半圆测试平台界面的ViewController
 */

#import "BanBu_WebFrame_ViewController.h"
#import "AppDataManager.h"
#import "CJSONSerializer.h"
#import "CJSONDeserializer.h"
#import "GTMBase64.h"
#import "NSDictionary_JSONExtensions.h"
#import "NSString+SBJSON.h"
#import "NSData+Base64.h"
#import "BanBu_FriendListWebViewController.h"
#import "BanBuAPIs.h"
#import "AppCommunicationManager.h"
#import "BanBu_NavButton.h"
#import "BanBu_ImageView.h"
#import "SFHFKeychainUtils.h"
#import "LeveyTabBarController.h"

@interface BanBu_WebFrame_ViewController ()

@end

@implementation BanBu_WebFrame_ViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = NSLocalizedString(@"HALFAREA", nil);
    
    BanBu_ImageView *img = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable]autorelease];

    img.frame = CGRectMake(0, 0, __MainScreen_Width, __MainScreen_Height);
    
    self.bgView = img;
    
    [self.view addSubview:self.bgView];
    
    _color = self.view.backgroundColor;
    
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 300, 80)];

    _inputView = textView;
    BanBu_ImageView *img1 = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeCell]autorelease];
    img1.frame  = CGRectMake(0,0, 300, 80);
    [textView insertSubview:img1 atIndex:0];
    textView.layer.borderColor = [[UIColor grayColor] CGColor];
    textView.layer.borderWidth = 1.0;
    textView.layer.cornerRadius = 6.0;
    textView.textColor = [UIColor darkTextColor];
    textView.font = [UIFont systemFontOfSize:16];
    _inputView.text = @"http://";
    _inputView.keyboardType = UIKeyboardTypeURL;
    [self.view addSubview:textView];
    [textView release];
    
    UIButton *sendBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    sendBtn.frame=CGRectMake(49, 125, 218, 40);
    [sendBtn setBackgroundImage:[[UIImage imageNamed:@"app_btn_blue.png"] stretchableImageWithLeftCapWidth:10.0 topCapHeight:0.0] forState:UIControlStateNormal];
    [sendBtn setTitle:NSLocalizedString(@"GO", nil) forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(loadHtmlPage) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sendBtn];
    
    UITapGestureRecognizer * tap  = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapped)];
    [self.view addGestureRecognizer:tap];
    self.view.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *doubleFingerOne = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                     action:@selector(handleDoubleFingerEvent:)];
    doubleFingerOne.numberOfTouchesRequired = 2;
    doubleFingerOne.numberOfTapsRequired = 2;
    doubleFingerOne.delegate = self;
    [self.view addGestureRecognizer:doubleFingerOne];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated
{
    [self.leveyTabBarController hidesTabBar:YES animated:YES];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [_friendListController.view removeFromSuperview];
}

-(void)loadHtmlPage
{
    [self tapped];
    
    if ([[_inputView.text lowercaseString] rangeOfString:@"goto"].location != NSNotFound)
    {
        //内容
        [MyAppDataManager.banbuHostIP setString:@""];
        
        [MyAppDataManager.banbuHostIP appendString:[NSString stringWithFormat:@"http://%@",[_inputView.text substringFromIndex:5]]];
        NSLog(@"MyAppDataManager.banbuHostIP:%@",MyAppDataManager.banbuHostIP);
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view point:self.navigationController.view.center title:@"切换服务器成功" activityAnimated:NO duration:2];
        return;
    }
    else if ([[_inputView.text lowercaseString] isEqualToString:@"koochat"])
    {//外网
        [MyAppDataManager.banbuHostIP setString:@""];
        
        [MyAppDataManager.banbuHostIP appendString:@"http://app.koochat.com"];
        BanBu_AppDelegate * app = (BanBu_AppDelegate *)[[UIApplication sharedApplication] delegate];
        [app getServerList];
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view point:self.navigationController.view.center title:@"切换服务器成功" activityAnimated:NO duration:2];
        return;
    }
    else if ([[_inputView.text lowercaseString] rangeOfString:@"cmd"].location != NSNotFound)
    {//取设备号
        
        BanBu_AppDelegate *ap = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
        
        //yinlinlin 2014年08月08日15:24:12 先使用pushid，获取不到的情况下使用systemUDID
        NSString *systemUDID;
        if(ap.pushid&&ap.pushid.length)
        {
            systemUDID = ap.pushid ;
        }
        else
        {
            systemUDID = [SFHFKeychainUtils getPasswordForUsername:@"halfeet_user_UUID" andServiceName:@"com.halfeet_halfeet" error:nil];
            
        }
        _inputView.text = systemUDID;
        return;
    }
    
    if (![self trimBlankString:_inputView.text].length)
    {
        return;
    }
    
    self.view.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.6];
    CGRect rect1;
    if(IS_IOS_7)
    {
        rect1 = CGRectMake(0, 20, __MainScreen_Width, __MainScreen_Height);
    }
    else
    {
        rect1 = CGRectMake(0, 0, __MainScreen_Width, __MainScreen_Height);
    }
    self.webview = [[[UIWebView alloc] initWithFrame:rect1] autorelease];
    
    NSURL *baseUrl = [NSURL URLWithString:_inputView.text];
    NSURLRequest * request = [NSURLRequest requestWithURL:baseUrl];
    [self.webview loadRequest:request];
    [self.webview setDelegate:self];
    
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];

    //iphone4原来版本是ios4，所以要适应版本
    if ([phoneVersion integerValue]<5)
    {
        for (id subview in self.webview.subviews)
            if ([[subview class] isSubclassOfClass: [UIScrollView class]])
                ((UIScrollView *)subview).bounces = NO;
    }
    else
    {
        self.webview.scrollView.bounces = NO;
    }
    
    self.webview.frame = rect1;
    CATransition *animation = [CATransition animation];
    animation.duration = .5f;
    animation.timingFunction=UIViewAnimationCurveEaseInOut;
    animation.fillMode = kCAFillModeForwards;
    animation.type = kCATransitionReveal;
    animation.subtype = kCATransitionFade;
   
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(__MainScreen_Width-40, 6,34, 34)];
    button.alpha = 0.7;
    [button setBackgroundImage:[UIImage imageNamed:@"cancelWeb.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(cancelView:) forControlEvents:UIControlEventTouchUpInside];
    [self.webview addSubview:button];

    [self.view.window.layer addAnimation:animation forKey:@"animation"];
    [self.navigationController.view addSubview:self.webview];
}

//去掉空格、空行
-(NSString *)trimBlankString:(NSString *)string
{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
    return string;
}

-(void)handleDoubleFingerEvent:(UITapGestureRecognizer *)dtap
{
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view point:self.navigationController.view.center title:MyAppDataManager.banbuHostIP activityAnimated:NO duration:2];
}
-(void)tapped
{
    [_inputView resignFirstResponder];
}

-(void)cancelView:(UIButton *)sender
{
    self.view.backgroundColor = _color;
    [self.webview removeFromSuperview];
}

-(void)popself
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *url = request.URL.absoluteString;//取到网址，并转成OC的字符串
    
    if ([url rangeOfString:@"hf_api_get_user_userid"].length > 0)
    {
        NSMutableDictionary * param = [NSMutableDictionary dictionaryWithCapacity:2];
        [param setValue:@"hf_api_get_user_userid" forKey:@"fc"];
        [param setValue:MyAppDataManager.useruid forKey:@"userid"];
        
        NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:param];
        jsonfrom = [[jsonfrom dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        
        
        NSString *js = [NSString stringWithFormat:@"hf_api_get_user_userid_back('%@')", jsonfrom];
        [webView stringByEvaluatingJavaScriptFromString:js];//调用网页中的JavaScript方法
        return NO;
    }
    else if ([url rangeOfString:@"hf_api_get_user_from_friendlist"].length > 0)
    {
        _friendListController = [[BanBu_FriendListWebViewController alloc]init];
        _friendListController.web = self;
        _friendListController.view.frame = self.navigationController.view.bounds;
        CATransition *animation = [CATransition animation];
        animation.duration = .5f;
        animation.timingFunction=UIViewAnimationCurveEaseInOut;
        animation.fillMode = kCAFillModeForwards;
        animation.type = kCATransitionReveal;
        animation.subtype = kCATransitionFade;

        [self.view.window.layer addAnimation:animation forKey:@"animation"];
        [self.navigationController.view addSubview:_friendListController.view];
        
        return NO;
    }
    else if([url rangeOfString:@"hf_api_send_msg_touser"].length > 0)
    {
        NSArray * paramArray = [url componentsSeparatedByString:@"///"];
        
        NSString * paramStr = [paramArray lastObject];
        
        NSMutableDictionary * paramDic = [NSMutableDictionary dictionaryWithCapacity:2];
        
        NSData *resFrom64 = [NSData dataFromBase64String:paramStr];
        
        [paramDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:nil]];
        
        NSDictionary * amsg = [self sendMsg:[paramDic valueForKey:@"says"] toUserid:[paramDic valueForKey:KeyUid]];
        NSString * linkTo = [amsg valueForKey:KeyLinkTo];//点击消息要跳转的页面（可以是url，半圆内应用、--游戏等）
        
        [MyAppDataManager writeToDetailChatTable:amsg andToUid:[paramDic valueForKey:KeyUid]];
        [MyAppDataManager updateDialogLinkTo:linkTo toUserID:[paramDic valueForKey:KeyUid] toChatID:[amsg valueForKey:KeyChatid]];
        
        //发送
        [MyAppDataManager sendMsg:[NSDictionary dictionaryWithObjectsAndKeys:amsg,KeySays,VALUE(KeyChatid, amsg),KeyChatid,nil] toUid:[paramDic valueForKey:KeyUid]];
        
        [paramDic setValue:@"hf_api_send_msg_touser" forKey:@"fc"];
        [paramDic setValue:@"y" forKey:@"ok"];
        
        NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:paramDic];
        jsonfrom = [[jsonfrom dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        
        NSString *js = [NSString stringWithFormat:@"hf_api_send_msg_touser_back('%@')", jsonfrom];
        [webView stringByEvaluatingJavaScriptFromString:js];//调用网页中的JavaScript方法
        
        return NO;        
    }
    else if([url rangeOfString:@"hf_api_get_phone_language"].length > 0)
    {
        NSMutableDictionary * param = [NSMutableDictionary dictionaryWithCapacity:2];
        [param setValue:@"hf_api_get_phone_language" forKey:@"fc"];
        [param setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
        
        NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:param];
        jsonfrom = [[jsonfrom dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        
        NSString *js = [NSString stringWithFormat:@"hf_api_get_user_loginid_back('%@')", jsonfrom];
        [webView stringByEvaluatingJavaScriptFromString:js];//调用网页中的JavaScript方法
        return NO;
    }
    return YES;
}

-(void)getSelectedUserInfo:(NSDictionary *)userInfoDic
{
    NSMutableDictionary * param = [NSMutableDictionary dictionaryWithDictionary:userInfoDic];
    
    [param setValue:@"hf_api_get_user_from_friendlist" forKey:@"fc"];
    
    
    NSString *jsonfrom = [[CJSONSerializer serializer] serializeDictionary:param];
    jsonfrom = [[jsonfrom dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    NSString *js = [NSString stringWithFormat:@"hf_api_get_user_from_friendlist_back('%@')", jsonfrom];
    [self.webview stringByEvaluatingJavaScriptFromString:js];//调用网页中的JavaScript方法
}

//包装says
-(NSDictionary *)sendMsg:(NSString *)saysDic toUserid:(NSString *)userid
{
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setLocale:[NSLocale currentLocale]];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *stime = [formatter stringFromDate:[NSDate date]];
    
    NSMutableDictionary *saysDictionary=[NSMutableDictionary dictionaryWithDictionary:[AppComManager getAMsgFrom64String:saysDic]];
    
    [saysDictionary setValue:stime forKey:KeyStime];

    NSString * chatID = [MyAppDataManager searchMaxChatid:userid];
    
    [saysDictionary setValue:chatID forKey:KeyChatid];
    if ([[saysDictionary valueForKey:KeyType] isEqualToString:@"url"])
    {
        [saysDictionary setValue:[NSNumber numberWithInt:ChatCellTypeSpecialText] forKey:KeyType];
    }
    return saysDictionary;
}

-(void)dealloc
{
    [_bgView release],_bgView = nil;
    [_webview release],_webview = nil;
    [_friendListController release],_friendListController = nil;
    [super dealloc];
}

@end
